<template>
  <div>
    <el-card title="发布新商品" class="app-container">
      <!--    <div slot="header" class="clearfix">-->
      <!--      <span>发布新商品</span>-->
      <!--    </div>-->
      <el-alert
        title="发布须知：准确选择类目有利于商品曝光，促进转化；若错放类目将会导致流量降权或下架整改。"
        type="warning"
        :closable="false"
      />
      <div class="pt20">
        选择分类
      </div>
      <div class="pt10">
        <el-autocomplete
          v-model="searchKw"
          :fetch-suggestions="querySearchAsync"
          style="width: 100%"
          @select="handleSelect"
          placeholder="请输入关键字搜索分类"
          size="mini"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
          <template slot-scope="{ item }">
            <span class="search__item" v-for="i in item" :key="i.id" v-html="i.title"></span>
          </template>
        </el-autocomplete>
      </div>
      <div class="category">
        <div class="category__group">
          <el-input v-model="firstCat" size="mini" clearable placeholder="一级分类：名称检索">
            <el-button slot="append" icon="el-icon-search"/>
          </el-input>
          <div class="category__list">
            <el-collapse v-if="filterFirstCatList.length" v-model="selectedStapleName">
              <el-collapse-item
                v-for="(cat) in filterFirstCatList"
                :key="cat.title"
                :name="cat.title"
                :title="cat.title"
              >
                <div
                  v-for="item in cat.list"
                  @click="handleSelectCat(item)"
                  class="category__item"
                  :class="{'category__item--selected':selectedFirstCatId === item.id}"
                  :key="item.id"
                >
                  {{ item.title }}
                </div>
              </el-collapse-item>
            </el-collapse>
            <div v-else>暂无相关分类</div>
          </div>
        </div>
        <div v-if="selectedFirstCatId" class="category__group" v-loading="isLoadingLevel === 1">
          <el-input v-model="secondCat" size="mini" placeholder="二级分类：名称检索">
            <el-button slot="append" icon="el-icon-search"/>
          </el-input>
          <div class="category__list">
            <div
              v-for="item in filterSecondCatList"
              :class="{'category__item--selected':selectedSecondCatId === item.id}"
              @click="handleSelectCat(item)"
              class="flex category__item"
              :key="item.id"
            >
              <div class="category__letter category__letter--first" v-if="item.isFirst">{{ item.firstLetter }}</div>
              <div class="category__letter" v-else></div>
              {{ item.title }}
            </div>
          </div>
        </div>
        <div v-if="selectedSecondCatId" class="category__group" v-loading="isLoadingLevel === 2">
          <el-input v-model="thirdCat" size="mini" placeholder="三级分类：名称检索">
            <el-button slot="append" icon="el-icon-search"/>
          </el-input>
          <div class="category__list">
            <div
              :class="{'category__item--selected':selectedThirdCatId === item.id}"
              v-for="item in filterThirdCatList"
              @click="handleSelectCat(item)"
              class="flex category__item"
              :key="item.id"
            >
              <div class="category__letter category__letter--first" v-if="item.isFirst">{{ item.firstLetter }}</div>
              <div class="category__letter" v-else></div>
              {{ item.title }}
            </div>
          </div>
        </div>
        <div v-if="selectedThirdCatId && forthCatList.length" class="category__group" v-loading="isLoadingLevel === 3">
          <el-input v-model="forthCat" size="mini" placeholder="四级分类：名称检索">
            <el-button slot="append" icon="el-icon-search"/>
          </el-input>
          <div class="category__list">
            <div
              v-for="item in filterForthCatList"
              @click="handleSelectCat(item)"
              class="flex category__item"
              :class="{'category__item--selected':selectedForthCatId === item.id}"
              :key="item.id"
            >
              <div class="category__letter category__letter--first" v-if="item.isFirst">{{ item.firstLetter }}</div>
              <div class="category__letter" v-else></div>
              {{ item.title }}
            </div>
          </div>
        </div>
      </div>
      <!--      <div class="pt30 text-center">-->
      <!--        <el-button type="primary" @click="handleToNewSpu">确定发布该类商品</el-button>-->
      <!--      </div>-->
    </el-card>
    <div class="btn-area-holder">
    </div>
    <div class="btn-area  btn-area--fixed text-center">
      <!--      <el-button type="primary" size="small" :loading="isSubmitting" @click="handleSubmit">提交并上架</el-button>-->
      <el-button type="primary" @click="handleToNewSpu">确定发布该类商品</el-button>
    </div>
  </div>

</template>

<script>
import {categoryApi} from '@/feature/pdt/infra/api/categoryApi'

export default {
  data() {
    return {
      searchKw: '',
      firstCat: '',
      secondCat: '',
      thirdCat: '',
      forthCat: '',
      isLoadingLevel: 0,

      selectedStapleName: '',
      selectedFirstCatId: 0,
      selectedSecondCatId: 0,
      selectedThirdCatId: 0,
      selectedForthCatId: 0,

      firstCatList: [],
      secondCatList: [],
      thirdCatList: [],
      forthCatList: []
    }
  },
  computed: {
    filterFirstCatList() {
      if (this.firstCatList.length > 0 && this.firstCat.trim()) {
        return this.firstCatList.reduce((r, el) => {
          const list = el.list.filter(i => i.title.toLowerCase().includes(this.firstCat.toLowerCase().trim()))
          if (list.length) {
            r.push({
              title: el.title,
              list
            })
          }
          return r
        }, [])
      }
      return this.firstCatList
    },
    filterSecondCatList() {
      if (this.secondCatList.length > 0 && this.secondCat.trim()) {
        return this.secondCatList.filter(i => i.title.toLowerCase().includes(this.secondCat.toLowerCase().trim()))
      }
      return this.secondCatList
    },
    filterThirdCatList() {
      if (this.thirdCatList.length > 0 && this.thirdCat.trim()) {
        return this.thirdCatList.filter(i => i.title.toLowerCase().includes(this.thirdCat.toLowerCase().trim()))
      }
      return this.thirdCatList
    },
    filterForthCatList() {
      if (this.forthCatList.length > 0 && this.forthCat.trim()) {
        return this.forthCatList.filter(i => i.title.toLowerCase().includes(this.forthCat.toLowerCase().trim()))
      }
      return this.forthCatList
    }
  },
  created() {
    categoryApi.firstCateList().then(data => {
      this.firstCatList = data
    })
  },
  methods: {
    querySearchAsync(queryString, cb) {
      queryString = queryString && queryString.trim() || ''
      if (!queryString || this.lastSearchKey === queryString) {
        cb(this.lastSearchData || [])
        return
      }
      if (this.isSearching) {
        return
      }
      this.isSearching = true
      categoryApi.search(queryString).then(data => {
        this.lastSearchData = data
        this.lastSearchKey = queryString
        cb(data)
      }).finally(() => {
        this.isSearching = false
      })
    },
    handleSelect(items) {
      this.firstCat = ''
      this.secondCat = ''
      this.thirdCat = ''
      this.forthCat = ''
      const firstCat = this.firstCatList.find(el => el.list.some(i => i.id === items[0].id))
      if (firstCat) {
        this.selectedStapleName = firstCat.title
        const proList = []
        if (this.selectedFirstCatId !== items[0].id) {
          proList.push(() => {
            this.selectedFirstCatId = items[0].id
            return this.handleSelectCat(firstCat.list.find(el => el.id === this.selectedFirstCatId))
          })
        }
        if (this.selectedSecondCatId !== items[1].id) {
          proList.push(() => {
            this.selectedSecondCatId = items[1].id
            return this.handleSelectCat(this.secondCatList.find(el => el.id === this.selectedSecondCatId))
          })
        }
        if (this.selectedThirdCatId !== items[2].id) {
          proList.push(() => {
            this.selectedThirdCatId = items[2].id
            return this.handleSelectCat(this.thirdCatList.find(el => el.id === this.selectedThirdCatId)).then(() => {
              this.selectedForthCatId = items[3] ? items[3].id : 0
            })
          })
        }
        if (items[3] && this.selectedThirdCatId !== items[3].id) {
          proList.push(() => {
            this.selectedForthCatId = items[3].id
            this.handleSelectCat(this.forthCatList.find(el => el.id === this.selectedForthCatId))
          })
        } else {
          this.selectedForthCatId = 0
        }
        let item = proList.shift()
        let pro = null
        while (item) {
          if (!pro) {
            pro = item()
          } else {
            pro = pro.then(item)
          }
          item = proList.shift()
        }
      }
    },
    handleSelectCat(cat) {
      if (cat.level === 0) {
        this.selectedFirstCatId = cat.id
        this.selectedSecondCatId = 0
        this.selectedThirdCatId = 0
        this.selectedForthCatId = 0
        this.secondCat = ''
        this.thirdCat = ''
        this.forthCat = ''
      } else if (cat.level === 1) {
        this.selectedSecondCatId = cat.id
        this.selectedThirdCatId = 0
        this.selectedForthCatId = 0
        this.thirdCat = ''
        this.forthCat = ''
      } else if (cat.level === 2) {
        this.selectedThirdCatId = cat.id
        this.selectedForthCatId = 0
        this.forthCat = ''
      } else {
        this.selectedForthCatId = cat.id
      }
      this.finalCategoryId = 0
      if (cat.isLeaf) {
        this.finalCategoryId = cat.id
        if (cat.level === 2) {
          this.forthCatList = []
        }
        return
      }
      this.isLoadingLevel = cat.level + 1
      return categoryApi.subCateList(cat.id).then(data => {
        if (cat.level === 0) {
          this.secondCatList = data
        } else if (cat.level === 1) {
          this.thirdCatList = data
        } else if (cat.level === 2) {
          this.forthCatList = data
        }
      }).finally(() => {
        this.isLoadingLevel = false
      })
    },
    handleToNewSpu() {
      if (!this.finalCategoryId) {
        this.$message.warning('请选择完整的分类')
        return
      }
      this.$router.push({path: '/pdt/spu/edit', query: {categoryId: this.finalCategoryId}})
    }
  }
}
</script>

<style lang="scss" scoped>
.category {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  border: 1px solid #eee;
  height: 500px;
  margin-top: 20px;

  &__group {
    padding: 10px;
    border-right: 1px solid #eee;
    display: flex;
    flex-direction: column;

  }

  &__list {
    flex: auto;
    flex-shrink: 0;
    height: 0;
    padding: 10px;
    overflow: auto;
    margin-top: 10px;
    font-size: 14px;
  }

  &__item {
    padding: 5px 10px;

    &:hover {
      background-color: #eee;
      cursor: pointer;
    }

    &--selected {
      background-color: #edf7ff;
    }
  }

  &__letter {
    width: 20px;
    height: 20px;
    text-align: center;
    line-height: 20px;
    margin-right: 10px;

    &--first {
      background-color: #aaa;
      color: #fff;
    }
  }
}

.search__item {
  position: relative;

  &:after {
    content: ' > ';
    display: inline-block;
    margin: 0 5px;
    font-size: 12px;
  }

  &:last-child {
    &:after {
      display: none;
    }
  }

  ::v-deep i {
    color: red;
    font-style: normal;
  }
}
</style>
